<template>
  <div class="hdgl-edit-step-2 flex">
    <!--        海报生成-->
    <div class="poster-container">
      <img v-if="background" class="poster-bg" :src="background" alt="背景图片"/>
      <div class="d-jcc-aic poster-bg" v-else>
        <img style="width: 64px;height:64px" :src="defaultPicture" alt="背景图片"/>
        <div class="poster-bg-desc d-jcc-aic">添加图片</div>
      </div>
      <div class="poster-box">
        <vue-draggable-resizable
          v-show="header.visible"
          :active="true"
          :x="header.x"
          :y="header.y"
          :w="header.size"
          :h="header.size"
          :min-width="50"
          :min-height="50"
          :class="{circle:header.circle}"
          prevent-deactivation
          :handles="['br']"
          parent
          lock-aspect-ratio
          :style="{backgroundColor: '#FAFAFA'}"
          @resizing="onHeaderResize"
          @dragstop="onHeaderDragStop">
          <div class="full-fill d-jcc-aic" :class="{circle:header.circle}" :style="{color: '#8D9EA6'}">头像</div>
          <img slot="br" class="stretch-icon" src="@/perm/assets/stretch.png">
        </vue-draggable-resizable>
        <vue-draggable-resizable
          v-show="nickname.visible"
          :active="true"
          :x="nickname.x"
          :y="nickname.y"
          :w="nickname.w"
          :h="nickname.h"
          prevent-deactivation
          :resizable="false"
          parent
          :style="{backgroundColor: '#FAFAFA'}"
          @dragstop="onNicknameDragStop">
          <div
            class="full-fill d-jcc-aic"
            :style="{color:nickname.color, textAlign:nickname.textAlign, fontSize: nickname.size * 4/3+'px'}">
            昵称
          </div>
          <img slot="br" class="stretch-icon" src="@/perm/assets/stretch.png">
        </vue-draggable-resizable>
        <vue-draggable-resizable
          v-show="qrCode.visible"
          :active="true"
          :x="qrCode.x"
          :y="qrCode.y"
          :w="qrCode.size"
          :h="qrCode.size"
          :min-width="50"
          :min-height="50"
          prevent-deactivation
          :handles="['br']"
          parent
          lock-aspect-ratio
          :style="{backgroundColor: '#FAFAFA'}"
          @resizing="onQrCodeResize"
          @dragstop="onQrCodeDragStop">
          <div class="full-fill d-jcc-aic" :style="{color: '#8D9EA6'}">二维码</div>
          <img slot="br" class="stretch-icon" src="@/perm/assets/stretch.png">
        </vue-draggable-resizable>
      </div>
    </div>
    <div class="poster-settings">
      <a-form-model
        ref="form"
        :model="model"
        labelAlign="right"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-form-model-item label="海报图片">
          <!--                    保存时才执行上传图片，保存失败要发起删除图片的请求-->
          <a-upload
            class="upload-demo ml-20"
            ref="upload"
            :action="uploadUrl"
            accept="image/*"
            :data="{dir: dir}"
            :showUploadList="false"
            @change="handleSuccess">
            <b-button
              type="primary"
              suffixIcon="cloud-upload"
              style="padding: 0 8px;width: 72px;height: 32px;"
              btnContent="上传"/>
            <a-button slot="trigger" size="small">选取文件</a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="用户头像">
          <div class="d-aic">
            <a-switch
              class="ml-20"
              v-model="header.visible">
            </a-switch>
            <span :style="{marginLeft:'8px',color:header.visible?'#46A0FC':''}">启用</span>
          </div>
          <div class="d-aic" v-if="header.visible">
            <div
              class="circle-avatar d-jcc-aic"
              style="margin-left: 26px"
              @click="header.circle=false"
              :class="{active:!header.circle}">方形
            </div>
            <div
              class="circle-avatar d-jcc-aic"
              style="margin-left: 16px"
              @click="header.circle=true"
              :class="{active:header.circle}">圆形
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item label="用户昵称">
          <a-switch
            class="ml-20"
            v-model="nickname.visible">
          </a-switch>
          <span :style="{marginLeft:'8px',color:header.visible?'#46A0FC':''}">启用</span>
          <div v-if="nickname.visible">
            <div class="ml-20 d-aic">
              <colorPicker v-model="nickname.color" class="color-picker-style"/>
              <div class="color-title">文字颜色</div>
            </div>
            <div class="ml-20 flex">
              <a-select
                v-model="nickname.size"
                placeholder="请选择"
                @change="changeNicknameSize"
                style="width: 90px">
                <a-select-option
                  v-for="n in 20"
                  :key="n">
                  {{ (n*3+9)+'pt' }}
                </a-select-option>
              </a-select>
              <div class="color-title">文字颜色</div>
            </div>
          </div>

        </a-form-model-item>
        <a-form-model-item label="二维码">
          <a-switch
            class="ml-20"
            v-model="qrCode.visible"
            disabled>
          </a-switch>
          <span :style="{marginLeft:'8px',color:qrCode.visible?'#46A0FC':''}">启用</span>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="poster-tip">
      <p>
        裂变海报说明：
      </p>
      <p>
        1. 建议尺寸 750*1334px，分辨率72，大小不超过1M
      </p>
      <p>
        2. 建议海报上二维码尺寸留白不小于150像素，分辨率72，二维码太小可能导致无法识别
      </p>
      <p>
        3. [头像][昵称][二维码]这些位置需要留空
      </p>
      <p>
        4. 海报其他内容不受限制，可自行设计
      </p>
      <p>
        5. 拖拉设置相应元素大小和位置
      </p>
    </div>
  </div>
</template>

<script>
  import VueDraggableResizable from 'vue-draggable-resizable'
  import 'vue-draggable-resizable/dist/VueDraggableResizable.css'
  import { keepN } from '../../../../utils'
  import defaultPicture from '@/perm/assets/default.png'

  export default {
    name: 'HdglEditStep2',
    components: {
      VueDraggableResizable
    },
    props: {
      model: {
        type: Object,
        default: () => {
        }
      }
    },
    data () {
      return {
        // 海报相对于750的缩放比例
        scale: 0.42,
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
        // 上传地址
        uploadUrl: 'api/file/upload',
        // 上传子目录
        dir: 'user/qw/poster',
        background: '',
        header: {},
        nickname: {},
        qrCode: {},
        defaultPicture

      }
    },
    methods: {
      fixLoaded (model, temp) {
        let num = 0
        if (temp) {
          num = 1
        } else {
          num = -1
        }
        // 获取海报地址
        this.getBackgroundUrl()
        if (!model.posterElements) {
          this.qrCode = {
            visible: true,
            size: 275,
            x: 25,
            y: 261
          }
          this.header = {
            visible: true,
            circle: false,
            size: 80,
            x: 25,
            y: 30
          }
          this.nickname = {
            visible: true,
            color: '#B42C2C',
            size: 18,
            x: 130,
            y: 30,
            w: 161,
            h: 46,
            // left center right
            textAlign: 'center'
          }
          return
        }
        try {
          // 加载到model后需要对海报数据进行格式化，同时对尺寸数据进行缩放
          const poster = JSON.parse(model.posterElements)
          this.header = Object.assign({}, {
            ...poster.header,
            x: this.formatPosterNum(poster.header.x, num),
            y: this.formatPosterNum(poster.header.y, num),
            size: this.formatPosterNum(poster.header.size, num)
          })

          this.nickname = Object.assign({}, {
            ...poster.nickname,
            x: this.formatPosterNum(poster.nickname.x, num),
            y: this.formatPosterNum(poster.nickname.y, num),
            w: this.formatPosterNum(poster.nickname.w, num),
            h: this.formatPosterNum(poster.nickname.h, num)
          })
          this.qrCode = Object.assign({}, {
            ...poster.qrCode,
            x: this.formatPosterNum(poster.qrCode.x, num),
            y: this.formatPosterNum(poster.qrCode.y, num),
            size: this.formatPosterNum(poster.qrCode.size, num)
          })
        } catch (e) {
          console.error(e)
        }
      },
      formatPosterNum (posterNum, num) {
        return this.formatPoster(posterNum) + num
      },
      formatPoster (posterNum) {
        const scale = this.scale
        return Number.parseInt(keepN(posterNum * scale, 0), 10)
      },
      loaded (model) {
        // 获取海报地址
        this.getBackgroundUrl()
        if (!model.posterElements) {
          this.qrCode = {
            visible: true,
            size: 275,
            x: 25,
            y: 261
          }
          this.header = {
            visible: true,
            circle: false,
            size: 80,
            x: 25,
            y: 30
          }
          this.nickname = {
            visible: true,
            color: '#B42C2C',
            size: 18,
            x: 130,
            y: 30,
            w: 161,
            h: 46,
            // left center right
            textAlign: 'center'
          }
          return
        }
        try {
          // 加载到model后需要对海报数据进行格式化，同时对尺寸数据进行缩放
          const poster = JSON.parse(model.posterElements)
          this.header = Object.assign({}, {
            ...poster.header,
            x: this.formatPoster(poster.header.x),
            y: this.formatPoster(poster.header.y),
            size: this.formatPoster(poster.header.size)
          })

          this.nickname = Object.assign({}, {
            ...poster.nickname,
            x: this.formatPoster(poster.nickname.x),
            y: this.formatPoster(poster.nickname.y),
            w: this.formatPoster(poster.nickname.w),
            h: this.formatPoster(poster.nickname.h)
          })
          this.qrCode = Object.assign({}, {
            ...poster.qrCode,
            x: this.formatPoster(poster.qrCode.x),
            y: this.formatPoster(poster.qrCode.y),
            size: this.formatPoster(poster.qrCode.size)
          })
        } catch (e) {
          console.error(e)
        }
      },
      getBackgroundUrl () {
        this.background = this.model.posterFileUrl
      },
      handleSuccess (e) {
        if (!e.file.response) {
          return
        }
        try {
          this.model.posterFileUrl = e.file.response.data.url
          this.getBackgroundUrl()
        } catch (e) {
          this.$message.error(`上传失败`)
        }
      },
      onHeaderResize (x, y, w, h) {
        this.header = Object.assign({}, {
          ...this.header,
          x: Math.floor(x),
          y: Math.floor(y),
          size: Math.floor(w)
        })
      },
      onHeaderDragStop (x, y) {
        this.header = Object.assign({}, {
          ...this.header,
          x: Math.floor(x),
          y: Math.floor(y)
        })
      },
      changeNicknameSize (s) {
        // 计算昵称需要的框框大小
        // 转换成px
        const fontSize = s * 4 / 3
        this.nickname = Object.assign({}, {
          ...this.nickname,
          w: fontSize * 2 + 20,
          h: fontSize + 10
        })
      },
      onNicknameDragStop (x, y) {
        this.nickname = Object.assign({}, {
          ...this.nickname,
          x: Math.floor(x),
          y: Math.floor(y)
        })
      },
      onQrCodeResize (x, y, w, h) {
        this.qrCode = Object.assign({}, {
          ...this.qrCode,
          x: Math.floor(x),
          y: Math.floor(y),
          size: Math.floor(w)
        })
      },
      onQrCodeDragStop (x, y) {
        this.qrCode = Object.assign({}, {
          ...this.qrCode,
          x: Math.floor(x),
          y: Math.floor(y)
        })
      },
      /**
       * 保存前上传图片
       */
      check () {
        // 保存前重新对数据格式化，并还原海报尺寸
        const scale = this.scale
        const poster = {
          header: {
            ...this.header,
            x: Number.parseInt(keepN(this.header.x / scale, 0), 10),
            y: Number.parseInt(keepN(this.header.y / scale, 0), 10),
            size: Number.parseInt(keepN(this.header.size / scale, 0), 10)
          },
          nickname: {
            ...this.nickname,
            x: Number.parseInt(keepN(this.nickname.x / scale, 0), 10),
            y: Number.parseInt(keepN(this.nickname.y / scale, 0), 10),
            w: Number.parseInt(keepN(this.nickname.w / scale, 0), 10),
            h: Number.parseInt(keepN(this.nickname.h / scale, 0), 10)
          },
          qrCode: {
            ...this.qrCode,
            x: Number.parseInt(keepN(this.qrCode.x / scale, 0), 10),
            y: Number.parseInt(keepN(this.qrCode.y / scale, 0), 10),
            size: Number.parseInt(keepN(this.qrCode.size / scale, 0), 10)
          }
        }
        console.log(poster)
        this.model.posterElements = JSON.stringify(poster)
        // 检查背景图片是否上传
        if (!this.model.posterFileUrl) {
          throw new Error('海报背景还未上传')
        }
      }
    }
  }
</script>

<style lang="less">
  .hdgl-edit-step-2 {

    .color-title {
      margin-left: 15px;
      font-size: 16px;
      color: #8C8C8C;
    }

    .ml-20 {
      margin-left: 20px;
    }

    .poster-container {
      position: relative;
      flex-shrink: 0;
      border: 4px solid #eee;
      box-sizing: content-box;
      width: 315px;
      height: 560px;
    }

    .poster-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      flex-direction: column;

      .poster-bg-desc {
        margin-top: 12px;
        width: 80px;
        height: 30px;
        border-radius: 4px;
        background-color: rgba(200, 205, 208, 100);
        color: rgba(255, 255, 255, 100);
        font-size: 14px;
      }
    }

    .poster-box {
      position: relative;
      width: 315px;
      height: 560px;
    }

    .vdr {
      transition: border-radius 1s ease 0s;
      border: 2px solid #e5e6e9;
      cursor: move;
    }

    .handle-br {
      bottom: 10%;
      right: 10%;
    }

    .poster-settings {
      flex-grow: 1;
      min-width: 350px;
      flex-shrink: 0;
      margin: 0 20px;
    }
  }

  .stretch-icon {
    width: 20px;
    height: 20px;
    position: absolute;
    left: -2px;
    top: -2px;
    background: #FAFAFA;
  }

  .full-fill {
    width: 100%;
    height: 100%;
  }

  .circle-avatar {
    width: 42px;
    height: 32px;
    line-height: 20px;
    border-radius: 4px;
    background-color: rgba(255, 255, 255, 100);
    color: rgba(140, 140, 140, 100);
    font-size: 14px;
    border: 1px solid rgba(217, 217, 217, 100);
    cursor: pointer;

    &.active {
      background-color: rgba(229, 247, 255, 100);
      color: rgba(24, 144, 255, 100);
      border: 1px solid rgba(165, 214, 255, 100);
    }
  }

  .color-picker-style {
    .colorBtn {
      width: 24px !important;
      height: 24px !important;
      border: 1px solid #BBBBBB;
    }

  }

</style>
